﻿using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace HaackMvcHelpers
{
    public static class ObjectHelpers
    {
        public static IDictionary<string, object> ToDictionary(this object o)
        {
            Dictionary<string, object> properties = new Dictionary<string, object>();

            foreach (PropertyValue property in o.GetProperties())
            {
                properties.Add(property.Name, property.Value);
            }
            return properties;
        }


        internal static IEnumerable<PropertyValue> GetProperties(this object o)
        {
            if (o != null)
            {
                PropertyDescriptorCollection props = TypeDescriptor.GetProperties(o);
                foreach (PropertyDescriptor prop in props)
                {
                    object val = prop.GetValue(o);
                    if (val != null)
                    {
                        yield return new PropertyValue { Name = prop.Name, Value = val };
                    }
                }
            }
        }
    }

    internal sealed class PropertyValue
    {
        public string Name { get; set; }
        public object Value { get; set; }
    }
}
